package guowei.guliorder.order.intercaptor;

import guowei.common.constant.SessionInfo;
import guowei.common.vo.MemberVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Iterator;

/**
 * 拦截器验证是否已经登录 传递的是用户信息
 *
 *  接收消息要解锁库存时，远程调用order服务，需要已登录状态，因此我们放行该远程请求
 */
public class OrderInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HashSet<String> set = new HashSet<>();
        set.add("/order/alipay");
        set.add("/order/order/getByOrderSn/**");
        String uri = request.getRequestURI();

//        boolean match = set.contains(uri);
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            String url = iterator.next();
            boolean match = new AntPathMatcher().match(url, uri);
            if (match){
                return true;
            }
        }



        MemberVo memberVo = (MemberVo) request.getSession().getAttribute(SessionInfo.SESSION_PREFIX);
        if (memberVo != null){
            threadLocal.set(memberVo);
            return true;
        }else {
            request.getSession().setAttribute("msg","请登录");
            response.sendRedirect("http://auth.ganjiuwanle.com/login.html");
            return false;
        }
    }
}
